﻿using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;

namespace UniFramework.Asset
{
    public class BaseAssetSystem
    {
        internal ResourcePackage _defaultPackage { get; set; }
        protected string packageVersion = "1.0.0";

        #region 基础生命周期管线

        public virtual async UniTask Init(string _defaultPackageName, Action initFinishCallBack)
        {
            YooAssets.Initialize();
            _defaultPackage = YooAssets.CreatePackage(_defaultPackageName);
            YooAssets.SetDefaultPackage(_defaultPackage);
            await UniTask.CompletedTask;
        }

        protected virtual async UniTask RequestPackageVersion()
        {
            var package = _defaultPackage;
            var operation = package.RequestPackageVersionAsync();
            await operation;
            if (operation.Status != EOperationStatus.Succeed)
            {
                throw new Exception("版本号更新失败，可能是找不到服务器");
            }

            packageVersion = operation.PackageVersion;
        }

        protected virtual async UniTask UpdatePackageManifest()
        {
            var package = _defaultPackage;
            var operation = package.UpdatePackageManifestAsync(packageVersion);
            await operation;
        }
        
        public virtual void Dispose()
        {
        }
        #endregion

        /// <summary>
        /// 请求一个资源加载器，由使用方自己管理销毁逻辑
        /// </summary>
        /// <param name="packName"></param>
        /// <returns></returns>
        public AssetLoader GetAssetLoader(string packName = "DefaultPackage")
        {
            ResourcePackage package = YooAssets.GetPackage(packName);
            AssetLoader assetLoader = new AssetLoader();
            assetLoader.OnInit(package);
            return assetLoader;
        }
    }
}